"""
    # @author:  zsj
    # @file:    session.py
    # @time:    2024/8/6 11:02
"""
from sqlmodel import SQLModel, Field, create_engine, Session, select
from config import SETTINGS
from src.core.logconfig import log

log = log.logger


class SQLConSqlite:

    def __init__(self):
        self.engine = create_engine(SETTINGS.DATABASE_SQLITE_URL, echo=SETTINGS.ECHO_SQL)

    def create_db_and_tables(self):
        log.info("正在初始化数据库表")
        SQLModel.metadata.create_all(self.engine)

    def db_query(self, entity):
        log.info("查询数据目标表：%s", str(entity.__tablename__))
        with Session(self.engine) as session:
            data_list = session.exec(select(entity)).all()
            log.info("查询数据：%s", str(data_list))
            return data_list

    def db_query_filter(self, entity, sql=None, single=False):
        log.info(f"查询数据表：{entity.__tablename__}")
        log.info(f"执行的SQL语句: {sql}")
        with Session(self.engine) as session:
            if sql is not None:
                if single:
                    data_list = session.exec(sql).first()
                else:
                    data_list = session.exec(sql).all()
            # log.info("查询数据：%s", str(data_list))
            if not data_list:
                return None
            return data_list

    def db_query_by_id(self, entity, id):
        log.info("查询数据目标表：%s", str(entity.__tablename__))
        log.info("查询数据目标表参数：id: %s", id)
        with Session(self.engine) as session:
            data_list = session.get(entity, id)
            log.info("查询数据：%s", str(data_list))
            if not data_list:
                return None
            return data_list

    def db_create(self, create, entity):
        log.info("新增数据目标表：%s", str(entity.__tablename__))
        with Session(self.engine) as session:
            db_model = entity.model_validate(create)
            session.add(db_model)
            session.commit()
            session.refresh(db_model)
            return db_model

    def db_update(self, entity, update):
        log.info("操作目标数据表：%s", str(entity.__tablename__))
        log.info("更新数据，参数id：%s", str(update.id))
        log.info("更新数据，参数：%s", str(update.__dict__))
        with Session(self.engine) as session:
            new_data = session.get(entity, update.id)
            if not new_data:
                return {"msg": "update before query not data", "exec": True}
            data = update.model_dump(exclude_unset=True)
            new_data.sqlmodel_update(data)
            session.add(new_data)
            session.commit()
            session.refresh(new_data)
            return new_data

    def db_del_by_id(self, entity, data_id):
        log.info("操作目标数据表：%s", str(entity.__tablename__))
        log.info("删除数据，参数id：%s", str(data_id))
        with Session(self.engine) as session:
            data = session.get(entity, data_id)
            if data:
                session.delete(data)
                session.commit()
                # session.refresh(data)
                return True
            else:
                return False

SQLCON = SQLConSqlite()

